<script>
import {addUserType, changeTypeName, deleteType, getUserType, updateStatus} from "./UserTypeJs";
import {formatDate} from "../../../util/js/utils";

export default {
  name: "UserType",
  data() {
    return {
      activeName: 'first',
      tableData: [],
      inputLength: 0
    };
  },
  mounted() {
    this.getTypes();
  },
  methods: {
    formatDate,
    // 获取用户类型列表
    getTypes() {
      getUserType('user', 'type').then(res => {
        this.tableData = [], // 将其设置以为空，保证不会在推入的时候造成多余的数据
          // 遍历数据
          res.data.forEach(item => {
            item.isEditing = false;
            this.tableData.push(item)
          })
      })
    },
    // 修改用户类型名称
    editTypeName(index, row) {
      if (row.isEditing) {
        // true，确认修改的操作
        if(this.inputLength<3 || this.inputLength>20) {
          this.$message.error("名称长度不符");
          return false;
        }
        changeTypeName(row.did, row.meaning).then(res => {
          if (res.code === '200') {
            this.$message.success("已将数据 " + (index + 1) + " 的名称修改为 " + row.meaning);
            this.getTypes()
          } else {
            console.log(res.msg);
          }
        }).catch(err => {
          console.log(err);
        })
      } else {
        // false，打开编辑的操作
        // 保存原来的值
        sessionStorage.setItem("oldType", row.meaning);
      }
      row.isEditing = !row.isEditing;
    },
    // 取消修改
    cancelEditTypeName(row) {
      row.meaning = sessionStorage.getItem('oldType');
      row.isEditing = false;
    },
    // 切换状态
    toggleStatus(row, index) {
      const _this = this;
      // 获取状态信息确定功能，禁用状态为启用功能，非禁用则为禁用功能
      if (row.status === '禁用') {
        // 启用
        updateStatus(row.did, '1').then(res => {
          if (res.code === '200') {
            _this.$message.success("数据" + (index + 1) + "启用成功!")
            // 获取数据
            _this.getTypes();
          } else {
            _this.$message.error(res.msg);
          }
        }).catch(error => {
          console.log("系统出错了!", error)
        })
      } else {
        // 禁用
        updateStatus(row.did, '0').then(res => {
          if (res.code === '200') {
            _this.$message.success("数据" + (index + 1) + "禁用成功!")
            // 获取数据
            _this.getTypes();
          } else {
            _this.$message.error(res.msg);
          }
        }).catch(error => {
          console.log("系统出错了!", error)
        })
      }
    },
    // 删除类型
    deleteType(index,row) {
      this.$confirm("是否删除数据"+(index+1)+"?","提示",{
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning"
      }).then(() => {
        deleteType(row.did).then(res => {
          if (res.code === '200') {
            this.$message.info("数据 "+(index+1)+" 已删除！")
            this.getTypes();
          }else{
            this.$message.error("删除失败:"+res.msg);
            console.log(res.msg);
          }
        }).catch(error => {
          this.$message.error("系统出错了")
          console.log(error);
        })
      }).catch(() => {
        this.$message.info("已取消删除")
      })

    },
    // 添加用户类型
    addUserType(){
      this.$prompt('请输入类型名称（3-10个字）', '添加', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\s\S]{3,20}$/,
        inputErrorMessage: '长度错误'
      }).then(({ value }) => {
        addUserType(value).then(res => {
          if(res.code === '200'){
            this.$message({
              type: 'success',
              message: '添加成功！ '
            });
            this.getTypes();
          }else{
            this.$message({
              type: 'error',
              message: '添加失败！ '
            });
          }
        }).catch(error => {
          this.$message({
            type: 'error',
            message: '系统出错了！ '
          });
          console.log(error);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    // 处理输入框输入长度限制
    handleInput(row) {
      this.inputLength = row.meaning.length;
    }
  }
}
</script>

<template>
  <div class="ut-main-container" id="ut-main-container">
    <el-tabs v-model="activeName" type="card" :stretch='true'>
      <el-tab-pane label="用户类型列表" name="first">
        <div class="ut-context-container">
          <el-table
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
              label="序号"
              type="index"
              width="50">
            </el-table-column>
            <el-table-column
              v-if=false
              prop="did">
            </el-table-column>
            <el-table-column
              prop="codeNumber"
              label="类型编号"
              align="center"
              width="80">
            </el-table-column>
            <el-table-column
              prop="meaning"
              label="类型名称"
              align="center"
              width="180">
              <template slot-scope="scope">
                <template v-if="scope.row.isEditing">
                  <el-input v-model="scope.row.meaning" placeholder="请输入"  :minlength="3" :maxlength="20" @input="handleInput(scope.row)">
                  </el-input>
                  <span v-if="scope.row.isEditing" style="color: red;font-size: 10px">请输入3-20个字的名称</span>
                </template>
                <template v-else>
                  {{ scope.row.meaning }}
                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              align="center"
              width="50">
              <template slot-scope="scope">
                <span :style="{ color: scope.row.status === '禁用' ? 'red' : 'green' }">{{ scope.row.status }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              align="center"
              width="100">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="修改时间"
              align="center"
              width="100">
              <template slot-scope="scope">
              <span :style="{ color: scope.row.updateTime === null ? 'red': ''}">
                {{ scope.row.updateTime === null ? '从未登录过' : formatDate(scope.row.updateTime) }}
              </span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteType(scope.$index, scope.row)"
                  type="text"
                  size="small">
                  删除
                </el-button>
                <el-button @click="editTypeName(scope.$index,scope.row)" type="text" size="small">
                  {{ scope.row.isEditing ? '确认修改' : '修改名称' }}
                </el-button>
                <el-button v-if="scope.row.isEditing" @click="cancelEditTypeName(scope.row)" type="text" size="small">
                  取消修改
                </el-button>
                <el-button @click="toggleStatus(scope.row,scope.$index)" type="text" size="small"
                           :style="{ color: scope.row.status === '禁用' ? 'green' : 'red' }">
                  {{ scope.row.status === '禁用' ? '启用' : '禁用' }}
                </el-button>
              </template>
              <template slot="header">
                操作
                <div style="display: flex; justify-content: space-between; align-items: center;float: right">
                  <el-button type="text" size="small" @click="addUserType">添加类型</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style>
@import "userTypeCss.css";
</style>
